<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <!-- 页面meta -->
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>电商管理后台</title>
    <link rel="shortcut icon" href="../favicon.ico">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/element-ui/index.css" />
    <link rel="stylesheet" href="../styles/common.css" />
    <link rel="stylesheet" href="../styles/index.css" />
    <link rel="stylesheet" href="../styles/icon/iconfont.css" />
    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body class="hold-transition">
<div id="app">
    <div class="app-container">
        <div class="box">
            <div class="filter-container">
                <el-input placeholder="商品编码/商品名称" v-model="pagination.queryString" style="width: 200px;" class="filter-item" clearable></el-input>
                <el-button @click="findPage()" class="dalfBut">查询</el-button>
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
            </div>
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                <el-table-column type="index" align="center" label="序号"></el-table-column>
                <el-table-column prop="id" label="商品编码" align="center"></el-table-column>
                <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
                <el-table-column prop="kindsName" label="商品分类" align="center"></el-table-column>
                <el-table-column prop="price" label="商品价格" align="center"></el-table-column>
                <el-table-column prop="number" label="商品销量" align="center"></el-table-column>
                <el-table-column prop="picture" label="商品图片" align="center" style="width: 50%;height: 50%">
                    <template slot-scope="scope">
                        <el-popover placement="top-start" title="" trigger="hover">
                            <img :src="getpicture(scope.row.picture)" alt="" style="width: 240px;height: 240px">
                            <img slot="reference" :src="getpicture(scope.row.picture)" style="width: 120px;height: 120px" alt="">
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        class="pagiantion"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-size="pagination.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
            <!-- 新增标签弹层 -->
            <div class="add-form">
                <el-dialog title="新增商品" :visible.sync="dialogFormVisible" @close="addDialogClosed">
                    <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="商品名称" prop="name">
                                    <el-input v-model="formData.name"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="分类名称" prop="kind">
                                    <el-select v-model="formData.kind" placeholder="请选择">
                                        <el-option v-for="(item,index) in GoodsKind" :key="index" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品价格" prop="price">
                                    <el-input v-model="formData.price"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品销量" prop="number">
                                    <el-input v-model="formData.number"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="商品图片">
                                    <el-upload
                                            class="avatar-uploader"
                                            action="/goods/upload"
                                            :auto-upload="autoUpload"
                                            name="imgFile"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleAdd()">确定</el-button>
                    </div>
                </el-dialog>
            </div>

            <!-- 编辑标签弹层 -->
            <div class="add-form">
                <el-dialog title="编辑商品" :visible.sync="dialogFormVisible4Edit" @close="editDialogClosed">
                    <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="商品名称" prop="name">
                                    <el-input v-model="formData.name"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="分类名称" prop="kind">
                                    <el-select v-model="formData.kind" placeholder="请选择">
                                        <el-option v-for="(item,index) in GoodsKind" :key="index" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品价格" prop="price">
                                    <el-input v-model="formData.price"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="商品销量" prop="number">
                                    <el-input v-model="formData.number"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="商品图片">
                                    <el-upload
                                            class="avatar-uploader"
                                            action="/goods/upload"
                                            :auto-upload="autoUpload"
                                            name="imgFile"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                        <el-button type="primary" @click="handleEdit()">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</div>
</body>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../plugins/axios/axios.min.js"></script>
<script src="../js/request.js"></script>
<script src="../api/login.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data (){
            var Nonnegativeinteger=(rule,value,callback) => {
                if(/^[1-9]\d*|0$/.test(value)){
                    callback();
                }else {
                    callback(new Error("输入必须为非负整数"))
                }
            }
            return {
                autoUpload:true,//自动上传
                imageUrl:null,//模型数据，用于上传图片完成后图片预览
                pagination: {//分页相关模型数据
                    currentPage: 1,//当前页码
                    pageSize:4,//每页显示的记录数
                    total:0,//总记录数
                    queryString:null//查询条件
                },
                dataList: [],//当前页要展示的分页列表数据
                formData: {},//表单数据
                dialogFormVisible: false,//增加表单是否可见
                dialogFormVisible4Edit:false,//编辑表单是否可见
                GoodsKind:[],
                rules: {//校验规则
                    name: [
                        { required: true, message: '商品名称为必填项', trigger: 'blur' },
                        { min: 1, max: 16, message: '商品名称在1~16个字符之间', trigger: 'blur'}
                    ],
                    kind: [{ required: true, message: '商品分类名称为必填项', trigger: 'blur' }],
                    price: [
                        { required: true, message: '商品价格为必填项', trigger: 'blur' },
                        { validator: Nonnegativeinteger, message: '价格为非负整数', trigger: 'blur'}
                    ],
                    number: [
                        { required: true, message: '商品销量为必填项', trigger: 'blur' },
                        { validator: Nonnegativeinteger, message: '销量为非负整数', trigger: 'blur'}
                    ]
                }
            }
        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            this.findPage();
            this.getGoodsKind();
        },
        methods: {
            //文件上传成功后的钩子，response为服务端返回的值，file为当前上传的文件封装成的js对象
            handleAvatarSuccess(response, file) {
                this.imageUrl='http://106.13.226.130:9000/goods/' + response.data;
                this.$message({
                    type:response.flag?'success':'error',
                    message:response.message
                });
                this.formData.picture=response.data;
                console.log(this.formData.picture);
            },
            //上传图片之前执行
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传套餐图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传套餐图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            getGoodsKind(){
                axios.get("/goods_kind/findAll").then((res) => {
                    this.GoodsKind = res.data.data;
                })
            },
            //编辑
            handleEdit() {
                this.$refs['dataEditForm'].validate((valid) => {
                    if(valid){
                        axios.put("/goods/edit",this.formData).then((res) => {
                            if(res.data.flag){
                                this.$message({
                                    type:'success',
                                    message:res.data.message
                                });
                            }else {
                                this.$message.error(res.data.message);
                            }
                        }).finally(() =>{
                            this.findPage();
                            this.dialogFormVisible4Edit=false;
                        });
                    }else {
                        this.$message.error("表单数据校验失败！");
                    }
                })
            },
            //添加
            handleAdd () {
                this.$refs['dataAddForm'].validate((valid) => {
                    if(valid){
                        console.log(this.formData);
                        axios.post("/goods/add",this.formData).then((res) => {
                            this.dialogFormVisible=false;
                            if(res.data.flag){
                                this.findPage();
                                this.$message({
                                    message:res.data.message,
                                    type:'success'
                                })
                            }else {
                                this.$message.error(res.data.message);
                            }
                        })
                    }else {
                        this.$message.error("数据校验失败，请检查你的输入信息是否正确！");
                        return false;
                    }
                })
            },
            //分页查询
            findPage() {
                var param={
                    currentPage: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    queryString: this.pagination.queryString
                };
                axios.post("/goods/pageQuery",param).then((res) => {
                    this.pagination.total=res.data.data.total;
                    this.dataList=res.data.data.records;
                })
            },
            // 重置表单
            resetForm() {
                this.formData={};
                this.imageUrl=null;
            },
            addDialogClosed(){
                this.$refs.dataAddForm.resetFields();
            },
            editDialogClosed(){
                this.$refs.dataEditForm.resetFields();
            },
            // 弹出添加窗口
            handleCreate() {
                this.dialogFormVisible=true;
                this.resetForm();
            },
            // 弹出编辑窗口
            handleUpdate(row) {
                this.dialogFormVisible4Edit=true;
                axios.get("/goods/findById?id="+row.id).then((res) => {
                    this.imageUrl='http://106.13.226.130:9000/goods/'+res.data.data.picture;
                    if(res.data.flag){
                        this.formData=res.data.data;
                        // console.log(this.formData)
                    }else {
                        this.$message.error(res.data.message);
                    }
                })
            },
            //切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage=currentPage;
                this.findPage();
            },
            // 删除
            handleDelete(row) {
                this.$confirm("你确定要删除当前数据吗？","提示",{
                    type: 'warning'
                }).then(() => {
                    axios.delete("/goods/delete?id="+row.id).then((res) => {
                        if(res.data.flag){
                            this.$message({
                                type:'success',
                                message:res.data.message
                            });
                            this.findPage();
                        }else {
                            this.$message.error(res.data.message);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type:'info',
                        message:"操作已取消"
                    });
                })
            },
            //显示图片
            getpicture(picture){
                return "http://106.13.226.130:9000/goods/"+picture;
            }
        }
    })
</script>
</html>